package com.fishing.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.sql.ast.expr.SQLCaseExpr.Item;
import com.alibaba.fastjson.JSON;
import com.fishing.entity.L_Item;
import com.fishing.util.ChangePropName;
import com.fishing.util.personal.DownLoadFile;
import com.fishing.util.personal.GetItemConfigString;

import QL.ButlerCdkeyGroupAbandonRequest;
import QL.ButlerCdkeyGroupAbandonResponse;
import QL.ButlerCdkeyGroupCodesDownloadRequest;
import QL.ButlerCdkeyGroupCodesDownloadResponse;
import QL.ButlerCdkeyGroupCodesQueryRequest;
import QL.ButlerCdkeyGroupCodesQueryResponse;
import QL.ButlerCdkeyGroupGenerateRequest;
import QL.ButlerCdkeyGroupGenerateResponse;
import QL.ButlerCdkeyGroupQueryRequest;
import QL.ButlerCdkeyGroupQueryResponse;
import QL.ButlerGetRechargeOrderListRequest;
import QL.ButlerGetRechargeOrderListResponse;
import QL.QLClient;
import net.sf.json.JSONArray;

/**
 * 激活码功能
 *
 * @author lrz
 */
@Controller
public class Activationcode {
    private static


    QLClient client = new QLClient();

    @RequestMapping("activation/toList")
    public ModelAndView toList(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("activationCode/getActivationCode");
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "activation/list", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public Map list(HttpServletRequest request, String FilterName, String start, String end, String PageIndex, String PageCount) {
        ButlerCdkeyGroupQueryRequest req = new ButlerCdkeyGroupQueryRequest();
        try {
            req.ZoneId = (Integer) request.getSession().getAttribute("ZoneId");
            req.FilterName = FilterName == "" ? "" : FilterName;
            req.IsFilterByCreateTime = start == "" ? false : true;
            if (req.IsFilterByCreateTime == true) {
                req.FilterCreateTimeBegin = start;
                req.FilterCreateTimeEnd = end;
            }
            req.PageIndex = Integer.parseInt(PageIndex) - 1;
            req.PageCount = Integer.parseInt(PageCount);
            ButlerCdkeyGroupQueryResponse rsp = new ButlerCdkeyGroupQueryResponse();
            if (req.ZoneId < 0)
                client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
            client.Execute(req, rsp);
            Map<String, Object> map = new HashMap<>();
            if (rsp.GroupList == null) {
                map.put("data", 0);
                map.put("count", 0);
                map.put("message", "");
                map.put("status", "200");
            } else {
                for (int i = 0; i < rsp.GroupList.size(); i++) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(rsp.GroupList.get(i).GroupRewards);
                    rsp.GroupList.get(i).GroupRewards = ChangePropName.PropSplice(sb);
                }
                map.put("data", rsp.GroupList);
                map.put("count", rsp.TotalCount);
                map.put("message", "");
                map.put("status", "200");
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("activationCode/addActivationCode")
    public ModelAndView addActivationCode(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("activationCode/addActivationCode");
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "activationCode/add", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String add(HttpServletRequest request, String formdata, String name, long Count) {
        L_Item item = JSON.parseObject(formdata, L_Item.class);
        HashMap<String, String> mapOld = new HashMap<String, String>();
        mapOld.put("Gold", item.getGold());
        mapOld.put("Diamond", item.getDiamond());
        mapOld.put("Vip", item.getVip());
        StringBuilder sb = new StringBuilder();

        Iterator<Map.Entry<String, String>> it = mapOld.entrySet().iterator(); //得这个集合的迭代器，保存在it里面
        while (it.hasNext())//迭代具有更多元素，返回true
        {
            Entry<String, String> entry = it.next(); //返回迭代的下一个元素
            if (!entry.getValue().equals("0")) {
                String itemConfig = GetItemConfigString.ItemConfigString(entry.getKey());
                if (!StringUtils.isEmpty(itemConfig)) {
                    if (sb.length() == 0)
                        sb.append('[');
                    else
                        sb.append(',');
                    sb.append('[');
                    sb.append(itemConfig);
                    sb.append(',');
                    sb.append(entry.getValue());
                    sb.append(']');
                }
            }
        }
        if (sb.length() > 0)
            sb.append(']');
        ButlerCdkeyGroupGenerateRequest req = new ButlerCdkeyGroupGenerateRequest();
        try {
            req.ZoneId = (Integer) request.getSession().getAttribute("ZoneId");
            req.GroupName = name;
            req.Count = Count;
            req.GroupRewards = sb.toString();
            ButlerCdkeyGroupGenerateResponse rsp = new ButlerCdkeyGroupGenerateResponse();
            if (req.ZoneId < 0)
                client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
            client.Execute(req, rsp);
            return rsp.ErrMsg;
        } catch (Exception e) {
            e.printStackTrace();
            return "添加失败";
        }
    }

    @RequestMapping("activationCode/seerecord")
    public ModelAndView seerecord(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("activationCode/seerecord");
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "activationCode/record", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public Map record(HttpServletRequest request,
                      String GroupId, String FilterStatus, String FilterCode,
                      String FilterUserId, String start, String end,
                      String PageIndex, String PageCount) {
        ButlerCdkeyGroupCodesQueryRequest req = new ButlerCdkeyGroupCodesQueryRequest();
        Map<String, Object> map = new HashMap<>();
        try {
            req.ZoneId = (Integer) request.getSession().getAttribute("ZoneId");
            req.GroupId = Integer.parseInt(GroupId);
            req.FilterStatus = Integer.parseInt(FilterStatus);
            if (req.FilterCode != "" || req.FilterCode != null) {
                req.FilterCode = FilterCode;
            }
            req.FilterUserId = FilterUserId == "" ? 0 : Integer.parseInt(FilterUserId);
            req.IsFilterByFetchedTime = start == "" ? false : true;
            if (req.IsFilterByFetchedTime == true) {
                req.FilterFetchedTimeBegin = start;
                req.FilterFetchedTimeEnd = end;
            }
            req.PageIndex = Integer.parseInt(PageIndex) - 1;
            req.PageCount = Integer.parseInt(PageCount);
            ButlerCdkeyGroupCodesQueryResponse rsp = new ButlerCdkeyGroupCodesQueryResponse();
            if (req.ZoneId < 0)
                client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
            client.Execute(req, rsp);
            if (rsp.CodeList != null) {
                map.put("data", rsp.CodeList);
                map.put("count", rsp.TotalCount);
                map.put("message", "");
                map.put("status", "200");
            } else {
                map.put("data", 0);
                map.put("count", 0);
                map.put("message", "");
                map.put("status", "200");
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("data", 0);
            map.put("count", 0);
            map.put("message", "");
            map.put("status", "200");
            return map;
        }

    }

    @RequestMapping("activationCode/toDownload")
    public ModelAndView toDownload(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("activationCode/todownload");
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "activationCode/download", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public void download(HttpServletRequest request, HttpServletResponse response, String GroupId, String State) throws Exception {
        ButlerCdkeyGroupCodesDownloadRequest req = new ButlerCdkeyGroupCodesDownloadRequest();
        try {
            req.ZoneId = (Integer) request.getSession().getAttribute("ZoneId");
            req.GroupId = Integer.parseInt(GroupId);
            req.Status = Integer.parseInt(State);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ButlerCdkeyGroupCodesDownloadResponse rsp = new ButlerCdkeyGroupCodesDownloadResponse();
        if (req.ZoneId < 0)
            client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
        client.Execute(req, rsp);
        String path = request.getSession().getServletContext().getRealPath("/") + "resource" + File.separator + "file" + File.separator + "激活码.txt";
        try {
            //把数据写入本地文件
            //获得工程根路径
            //System.out.println(request.getSession().getServletContext().getRealPath("/"));
            OutputStream fos = new FileOutputStream(path);
            fos.write(rsp.Codes.getBytes("UTF-8"));
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        //检测是域名还是ip
        String[] Domain = request.getServerName().split("\\.");
        if (Domain.length == 1)   //localhost
            response.sendRedirect(request.getContextPath() + "/login");
        else if (Domain.length == 3) //域名
            response.sendRedirect("/login");
        else {  //IP
            response.sendRedirect(request.getContextPath() + "/login");
        }
    }

    @ResponseBody
    @RequestMapping(value = "activationCode/Abandon", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String Abandon(HttpServletRequest request, String GroupId) {
        ButlerCdkeyGroupAbandonRequest req = new ButlerCdkeyGroupAbandonRequest();
        req.ZoneId = (Integer) request.getSession().getAttribute("ZoneId");
        req.GroupId = Integer.parseInt(GroupId);
        ButlerCdkeyGroupAbandonResponse rsp = new ButlerCdkeyGroupAbandonResponse();
        if (req.ZoneId < 0)
            client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
        client.Execute(req, rsp);
        return rsp.ErrMsg;
    }

    @ResponseBody
    @RequestMapping("activationCode/Downloadlist")
    public void Downloadlist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getSession().getServletContext().getRealPath("/") + "resource" + File.separator + "file" + File.separator + "激活码.txt";
        DownLoadFile.doGet(request, response, path);
    }
}
